package com.lulee007.rxjavarestunittestdemo.Services;

import com.google.gson.annotations.SerializedName;
import com.lulee007.rxjavarestunittestdemo.Models.FVideo;

import java.util.ArrayList;
import java.util.List;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.http.GET;
import retrofit.http.Path;
import rx.Observable;
import rx.functions.Func1;

/**
 * User: lulee007@live.com
 * Date: 2015-12-04
 * Time: 11:36
 */
public class FVideoService {
    private static  final  String WEB_SERVICE_BASE_URL="http://funnyv.sinaapp.com/funnyv/api/v1.0";
    private  FVideoWebService fVideoWebService;

    public FVideoService(){
        RequestInterceptor requestInterceptor=new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Accept","application/json");
                request.addHeader("Content-Type","application/json");
            }
        };
        RestAdapter restAdapter=new RestAdapter.Builder()
                .setEndpoint(WEB_SERVICE_BASE_URL)
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setRequestInterceptor(requestInterceptor)
                .build();

        fVideoWebService=restAdapter.create(FVideoWebService.class);
    }

    private  interface  FVideoWebService{
        @GET("/videos/type/{type}/page/{page}")
        Observable<VideoListDataEnvelope> fetchVideo(@Path("type") int type,
                                                     @Path("page") int page);
    }

    private class FunnyVideoDataEnvelope{
        @SerializedName("code")
        private int resultCode;

        private String msg;

        public Observable filterWebServiceErrors(){
            if(resultCode==0){
                return Observable.just(this);
            }else{
                return Observable.error(new Exception(msg));
            }
        }
    }

    private  class  VideoListDataEnvelope extends  FunnyVideoDataEnvelope{
        @SerializedName("content")
        private VideoListPage videoListPage;
    }

    public class  VideoListPage {
        @SerializedName("data")
        public  ArrayList<FVideo> videos;
        @SerializedName("total_count")
        public  int count;
    }

    public  Observable<VideoListPage> fetchVideos(int type,int page){
        return fVideoWebService.fetchVideo(type, page).flatMap(new Func1<VideoListDataEnvelope, Observable<? extends VideoListDataEnvelope>>() {
            @Override
            public Observable<? extends VideoListDataEnvelope> call(VideoListDataEnvelope videoListPage) {
                return videoListPage.filterWebServiceErrors();
            }
        }).map(new Func1<VideoListDataEnvelope, VideoListPage>() {
            @Override
            public VideoListPage call(VideoListDataEnvelope fVideos) {
                return fVideos.videoListPage;
            }
        });
    }
}
